<?php

class Application_Model_Cart extends Application_Model_DomainObject {

    protected $_id;

    /**
     * 购物车编号
     */
    protected $_cartId;
    protected $_userId;
    protected $_dateCreated;
    protected $_items;
    public $_maxItemsCount = 30;
    protected $_shops;
    protected $_isSeleted;

    /**
     * 返回当前购物车所有产品项
     * @return array 
     */
    public function getItems() {
        if (null == $this->_items) {
            $this->_items = Application_Model_CartItem::getByCartId($this->Id);
        }
        return $this->_items;
    }

    /**
     * 购物车总额 
     */
    public function getTotal() {
        return $this->getProductTotal() + $this->getShipFeeTotal();
    }

    /**
     * 商品总额
     * @return type 
     */
    public function getProductTotal() {
        $sum = 0;
        foreach ($this->getItems() as $item) {
            if($item->IsSelected)
                $sum+= $item->SubTotal;
        }
        return $sum;
    }

    /**
     * 运费总额
     * @return type 
     */
    public function getShipFeeTotal() {
        $sum = 0;
        foreach ($this->getShops() as $shop) {
            $sum+= $this->getShopMaxShipFee($shop->Id);
        }
        return $sum;
    }

    /**
     * 因为一个店铺只收一次运费,所以按最大价格收一次运费
     * @param int $shopId
     * @return number 
     */
    private function getShopMaxShipFee($shopId) {
        $shopItems = $this->getItemsByShopId($shopId);
        $fees = array();
        
        foreach ($shopItems as $item){
            if($item->IsSelected)
                array_push($fees, $item->ShipFee);
        }
        if(count($fees)>0){
            return max($fees);
        } else {
            return 0;
        }
    }

    /**
     * 返回当前购物车产品的所有店家
     * @return array 
     */
    public function getShops($IsSelected = FALSE) {
        if (NULL != $this->_shops) {
            return $this->_shops;
        }

        $this->_shops = array();
        $items = $this->getItems();
        $shopIds = array();
        foreach ($items as $item) {
            if($IsSelected){
                if($item->IsSelected){
                    if (in_array($item->ShopId, $shopIds))
                        continue;
                    array_push($shopIds, $item->ShopId);
                    array_push($this->_shops, $item->Shop);
                }
            } else {
                if (in_array($item->ShopId, $shopIds))
                    continue;
                array_push($shopIds, $item->ShopId);
                array_push($this->_shops, $item->Shop);
            }
        }
        return $this->_shops;
    }

    /**
     * 返回ShopID返回对应的购物车商品 
     * @return array
     */
    public function getItemsByShopId($shopId) {
        $items = $this->getItems();

        $result = array();
        foreach ($items as $item) {
            if ($item->ShopId == $shopId) {
                array_push($result, $item);
            }
        }
        return $result;
    }

    /**
     * 返回当前用户的购物车对象
     * @param bool $isOnlySelected 是否只显示选中的商品
     * @return Application_Model_Cart
     */
    public static function current($isSelected = TRUE) {
        $user = Application_Model_User::current();
        $cookieCart = false;
        $userCart = false;
        if (isset($_COOKIE[CART_ID])){
            $cookieCart = Application_Model_Cart::getByCartId($_COOKIE[CART_ID]);
        } 
        if ($user) {
            $userCart = Application_Model_Cart::getByUserId($user->Id);
        } 
        if(($cookieCart && $userCart && $cookieCart->UserId == $user->Id) || (!$cookieCart && $userCart) ){
            $cartId = $userCart->cartId;
        }
        else if (($cookieCart && !$userCart && $cookieCart->UserId == null) || ($cookieCart && $userCart && $cookieCart->UserId == null)){
            $cartId = $cookieCart->cartId;
        }
        else {
            $cartId = uniqid().rand(1, 100000);
        }
        setcookie(CART_ID, $cartId, time() + 365 * 24 * 3600,'/');
        
        $cart = Application_Model_Cart::getByCartId($cartId);
        if (null == $cart) {
            $cart = new Application_Model_Cart();
            $cart->CartId = $cartId;
            $cart->UserId = $user == null ? NULL : $user->Id;
            $cart->DateCreated = date('Y-m-d H:i:s');
            $cart->save();
        }

        $cart->IsSeleted = $isSelected;
        return $cart;
    }

    /**
     * 更新购物车
     * @param type $userId
     */
    public static function updateCart($userId) {
        $currentCart = Application_Model_Cart::current();
        if($currentCart && $currentCart->UserId != null){
            return;
        }
        if ($currentCart->UserId == $userId) {
            return;
        }
        $currentCart->UserId = $userId;
        $currentCart->save();
        $userCartAll = Application_Model_Cart::getDao()->queryAll(array("userId = "=>$userId));
        foreach ($userCartAll as $userCartVal) {
            if($userCartVal->Id == $currentCart->Id){
                continue;
            }
            foreach ($userCartVal->getItems() as $item) {
                $item->CartId = $currentCart->Id;
                $item->save();
            }
            $userCartVal->delete();
        }
        return ;
    }

    /**
     * 根据cartId返回一个cart对象
     * @param string $cartId
     * @return Application_Model_Cart
     */
    public static function getByCartId($cartId) {
        $db = new Application_Model_DbTable_Cart();
        return $db->getByCartId($cartId);
    }

    /**
     * 根据UserID返回Cart对象
     * @param int $userId
     * @return Application_Model_Cart
     */
    public static function getByUserId($userId) {
        return self::getDao()->queryOne(array('userId' => $userId));
    }

    /**
     * 添加一个产品到购物车
     * @param Application_Model_Product $product 产品
     * @param int $quantity 数量
     * @return Application_Model_CartItem
     */
    public function addCartItem($product, $quantity, $comment = '') {
        $this->_items = null;
        //遍历现有的购物车，如果已经有相同的产品，则数量相加，并直接返回此产品
        foreach ($this->getItems() as $item) {
            if ($item->ProductId == $product->Id) {
                $item->quantity += $quantity;
                if ($comment == '填写商品备注')
                    $comment = '';
                $item->comment .= $comment;
                $item->save();
                //修改记录到临时表
                Application_Model_TemporaryCart::addTemporaryLog($this->_id, $item->Id, $item->ProductName, $item->quantity, Application_Model_TemporaryCart::Type_Edit, $this->_userId);
                return $item;
            }
        }

        //如果此产品还未添加，则新增到购物车
        $cartItem = new Application_Model_CartItem();
        $cartItem->CartId = $this->Id;
        $cartItem->ProductName = $product->Name;
        $cartItem->quantity = $quantity;
        $cartItem->ProductId = $product->Id;
        $cartItem->DateCreated = date('Y-m-d H:i:s');
        $cartItem->Comment = $comment;
        $cartItem->Price = $product->Price;
        $cartItem->ShipFee = $product->ShipFee;
        $cartItem->ShopId = $product->ShopId;
        $cartItem->SkuNo = $product->Sku;
        $cartItem->Image = $product->RemoteImage;
        $cartItem->IsSelected = TRUE;
        $cartItem->save();
        //添加记录到临时表
        Application_Model_TemporaryCart::addTemporaryLog($this->_id, $cartItem->Id, $cartItem->ProductName, $cartItem->quantity, Application_Model_TemporaryCart::Type_Add, $this->_userId);
        return $cartItem;
    }

    /**
     * 清空购物车
     */
    public function clear() {
        Application_Model_CartItem::clearCart($this->Id);
    }

    public function createOrders($couponArr) {
        $shops = $this->getShops(true);
        $result = array();
        $userId = Application_Model_User::current()->Id;
        foreach ($shops as $shop) {
            $order = new Application_Model_Order();
            $order->DateCreated = date('Y-m-d H:i:s');
            $order->Status = Application_Model_Order::STATUS_PAYING;
            $order->problem = Application_Model_Order::Problem_Default;
            //$order->UserId = Application_Model_User::current()->Id;
            $order->Isdelete = 0;
            $productTotal = 0;
            $fees = array();
            foreach ($this->getItemsByShopId($shop->Id) as $item) {
                //提交代购记录到临时表
                Application_Model_TemporaryCart::addTemporaryLog($this->_id, $item->Id, $item->ProductName, $item->quantity, Application_Model_TemporaryCart::Type_Submit, $this->_userId);
                $orderItem = new Application_Model_OrderItem();
                $orderItem->ProductId = $item->ProductId;
                $orderItem->Price = $item->Price;
                $orderItem->Quantity = $item->Quantity;
                $orderItem->ProductName = $item->ProductName;
                $orderItem->Comment = $item->Comment;
                $orderItem->CkPass = 0;
                $order->addItem($orderItem);
                $fees[] = $item->ShipFee;
                $productTotal += $item->SubTotal;
            }
            $order->ShipFee = max($fees);
            $order->Sum = $productTotal + $order->ShipFee;
            $discount = 0;
            $coupon = false;
            if ($couponArr[$shop->Id]["couponNo"] != '0') {
                $coupon = Application_Model_Coupon::getByNo($couponArr[$shop->Id]["couponNo"]);
                $couponResult = $coupon->Validate($userId, $order->Sum, $couponArr[$shop->Id]["password"],0);
                if($couponResult->result){
                    $discount = $couponResult->discount;
                    $coupon->Status = Application_Model_Coupon::STATUS_USED;
                    $coupon->UseType = Application_Model_Coupon::useType_Order;
                }
            }
            $order->Discount = $discount;
            $order->productTotal = $productTotal;
            $order->CkPass = 0;
            $order->Scheme = 0;
            $order->isAbnormal = Application_Model_Order::Abnormal_Default;
            $result[$shop->Id]["order"] = $order;
            $result[$shop->Id]["coupon"] = $coupon;
        }
        return $result;
    }

}